#include <iostream>
#include <sstream>
#include "ImplicitTreap.h"
#include <string>
#include <vector>

using namespace std;

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(getline(ss, item, delim) || getline(ss, item, '\0')) {
        elems.push_back(item);
    }
    return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

//нумерация эл-тов в массиве начинается с 1, если в нем n эл-тов, то вставить элемент можно только на позицию <=n+1


int main() {
	Treap treap;
	bool work=true;
	/*insert(&tree, 1, 1);
	insert(&tree, 2, 2);
	insert(&tree, 3, 3);
	print(tree);
	remove(&tree, 2);
	cout<<"========"<<endl;
	print(tree);*/
	while (work) {
		string command;
		getline(cin, command);
		//command.append(" ");
		vector<string> args=split(command, ' ');
		if (!args.empty()) {
			if (args[0]=="add") {
				if (args.size()!=2) {
					cout<<"wrong use of add"<<endl;
				} else {
					int elem=atoi(args[1].c_str());
					treap.add(elem);
				}
			} else if (args[0]=="insert"){
					if (args.size()!=3) {
					cout<<"wrong use of insert"<<endl;
					} else {
						int elem=atoi(args[1].c_str());
						int pos=atoi(args[2].c_str());
						if (pos<1 || pos>treap.size()+1) {
							cout<<"wrong position of element"<<endl;
						} else {
							treap.insert(pos, elem);
						}
					} 
			} else if (args[0]=="delete") {
				if (args.size()!=2) {
					cout<<"wrong use of delete"<<endl;
				} else {
					int pos=atoi(args[1].c_str());
					if (pos<1 || pos>treap.size()+1) {
						cout<<"wrong position of element"<<endl;
					} else {
						treap.deleteNode(pos);
					}
				}
			} else if (args[0]=="sum") {
				if (args.size()!=3) {
					cout<<"wrong use of sum"<<endl;
				} else {
					int start=atoi(args[1].c_str());
					int end=atoi(args[2].c_str());
					if (start>end || start<1 || end>treap.size()) {
						cout<<"wrong positions of elemnt"<<endl;
					} else {
						cout<<treap.sum(start, end)<<endl;;
					}
				}
			} else if (args[0]=="print") {
				treap.show();
			} else if (args[0]=="exit") {
				work=false;
			} else {
				cout<<"unknown command"<<endl;
			}
		}
	}
	system("pause");
	return 0;
}